package team.you.change.service.serviceImpl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import team.you.change.dao.ApplyMapper;
import team.you.change.dao.TableMapper;
import team.you.change.pojo.Apply;
import team.you.change.service.ApplyService;
import team.you.change.util.Result;
import team.you.change.util.YuoUtil;

import javax.annotation.Resource;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

@Service
public class ApplyServiceImpl implements ApplyService {
    @Autowired
    private ApplyMapper applyMapper;

     @Override
    public Result add(Apply apply) {
        Result result = new Result();
        String uuid = UUID.randomUUID().toString();
        apply.setId(uuid);
        try {
            return YuoUtil.crudMsg(applyMapper.insert(apply), result);
        }catch (Exception e){
            return YuoUtil.setErrorMsg(e, result);
        }
    }

    @Override
    public Result check(Integer id, Integer type) {
        if(type == 0) return checkOld(id);
        else if (type == 1) return checkNew(id);
        else return null;
    }

    /**
     * 检查被调整课程是否被调整
     * @param id 课程id
     * @return
     */
    private Result checkNew(Integer id) {
        Result result = new Result();
        List<Apply> applies = applyMapper.selectByNewID(id);
        return checkList(applies, result);
    }
    /**
     * 检查课程能否调整
     * @param id 课程id
     * @return
     */
    private Result checkOld(Integer id) {
        Result result = new Result();
        List<Apply> applies = applyMapper.selectByOldID(id);
        return checkList(applies, result);
    }

    /**
     * 检查列表中是否有为满足条件的项
     * @param applies 列表
     * @param result 返回值
     * @return
     */
    private Result checkList(List<Apply> applies, Result result){
        Iterator<Apply> iterator = applies.iterator();
        while (iterator.hasNext()){
            Apply next = iterator.next();
            if(next.getState() == 2 || next.getState() == 3){
                continue;
            }else{
                result.setCode(500);
                result.setMsg("此课程正在调整！");
                return result;
            }
        }
        return result;
    }

}
